import * as CryptoJS from 'crypto-js';
// 密钥，需要将十六进制字符串转换为字节数组
const keyHex = '439c02ec9885cac78406642fad787baa';
const key = CryptoJS.enc.Hex.parse(keyHex);

// 偏移量（初始化向量），同样转换为字节数组
const ivHex = 'ac13712f3dbe2442a606790b31cbc803';
const iv = CryptoJS.enc.Hex.parse(ivHex);

export default {
  // 加密
  encrypt(plaintext) {
    const encrypted = CryptoJS.AES.encrypt(plaintext, key, {
      iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7,
    });
    return encrypted.ciphertext.toString(CryptoJS.enc.Base64);
  },
  // 解密
  decrypt(ciphertextBase64) {
    const ciphertext = CryptoJS.enc.Base64.parse(ciphertextBase64);
    const encryptedHexStr = CryptoJS.enc.Hex.stringify(ciphertext);
    const decrypted = CryptoJS.AES.decrypt(
      CryptoJS.lib.CipherParams.create({
        ciphertext: CryptoJS.enc.Hex.parse(encryptedHexStr),
      }),
      key,
      {
        iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
      }
    );
    return decrypted.toString(CryptoJS.enc.Utf8);
  },
};
